package top.itlir.edc.service.impl;

import javax.annotation.Resource;

import org.apache.commons.lang.math.RandomUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import top.itlir.edc.dao.UserRepository;
import top.itlir.edc.domain.Role;
import top.itlir.edc.domain.User;
import top.itlir.edc.service.IUserService;
import top.itlir.edc.utils.MD5Utils;

@Service
@Transactional
public class UserServiceImpl implements IUserService {
	
	@Resource
	private UserRepository userRepository;

	@Override
	public User findUserByUsername(String username) {
		return userRepository.findByUsername(username);
	}

	@Override
	public Page<User> pageQuery(Specification<User> spec, Pageable pageable) {
		return userRepository.findAll(spec, pageable);
	}

	@Override
	public void save(User model, Integer[] roleIds) {
		model.setPassword(MD5Utils.md5(model.getPassword()));
		userRepository.save(model);
		
		if (null != roleIds &&  roleIds.length > 0) {
			for (Integer roleId : roleIds) {
				Role role = new Role();
				role.setId(roleId);
				model.getRoles().add(role);
			}
		}
	}

}
